<template>
  <div class="products-list-wrap">
    <el-container>
      <el-aside width="200px">
        <el-tree
          :default-expand-all="false"
          :data="treeData"
          :props="{
            children: 'children',
            label: 'name'
          }"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node text-over">
              <span class="text-over" :title="node.label">{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </el-aside>
      <el-main>
        <div class="left" style="height: 100%">
          <div class="right-list-wrap" v-infinite-scroll="load" infinite-scroll-distance="5" :infinite-scroll-immediate="false">
            <div class="action-wrap">
              <div class="sort-wrap">
                <div class="left">
                  <p>排序：</p>
                  <el-button :class="{ active: currentSort.sortType === 1 }" text bg @click="changeSort(1)">
                    销量<el-icon>
                      <Sort />
                    </el-icon>
                  </el-button>
                  <el-button :class="{ active: currentSort.sortType === 2 }" text bg @click="changeSort(2)">
                    价格<el-icon>
                      <Sort />
                    </el-icon>
                  </el-button>
                  <el-button :class="{ active: currentSort.sortType === 3 }" text bg @click="changeSort(3)">
                    新品<el-icon>
                      <Sort />
                    </el-icon>
                  </el-button>
                </div>
                <div class="right ml20">
                  <p>价格范围：</p>
                  <div>
                    <el-input
                      type="number"
                      min="0"
                      v-model="minPrice"
                      placeholder="请输入"
                      @change="changeMinPrice"
                      style="width: 90px"
                    ></el-input>
                    <i> 至 </i>
                    <el-input
                      type="number"
                      min="0"
                      v-model="maxPrice"
                      placeholder="请输入"
                      @change="changeMaxPrice"
                      style="width: 90px"
                    ></el-input>
                  </div>
                </div>
              </div>
              <el-input
                class="searchkey-input ml20"
                v-model="searchkey2"
                clearable
                style="width: 220px"
                placeholder="请输入商品名、id、sku编码"
                :suffix-icon="Search"
                @change="getList"
                @clear="
                  () => {
                    getList();
                  }
                "
              />
              <div style="flex: 1; text-align: right">
                <el-button type="primary" link @click="isOpen = true">更多筛选</el-button>
              </div>
            </div>

            <div class="list-wrap">
              <template v-if="list.length > 0">
                <div class="list-item" v-for="item in list" :key="item.id">
                  <div>
                    <div class="prod-info">
                      <div class="top">
                        <div class="img"><img :src="item.mainPicUrl" alt="" /></div>
                        <div class="info">
                          <h3 class="name text-over" style="max-width: 300px">{{ item.productName || "-" }}</h3>
                          <p style="white-space: break-spaces; word-break: break-all">上架类目：{{ item.preview || "-" }}</p>
                          <p>型号：{{ item.modeCode || "-" }}</p>
                          <p>ID：{{ item.productId || "-" }}</p>
                        </div>
                      </div>
                      <footer>
                        <div>
                          <p>
                            价格：<span style="color: #ff3333">¥{{ item.businessLowestPrice || "-" }}</span>
                          </p>
                          <el-button type="primary" size="small" @click="openSku(item)">添加</el-button>
                        </div>
                        <!-- <div class="tips">备注：{{ item.remark || "-" }}</div> -->
                      </footer>
                      <!-- 右上仓库角标 -->
                      <!-- <div class="warehouse-icon">xx</div> -->
                    </div>
                  </div>
                </div>
              </template>
              <div v-else style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" />
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 更多属性、规格筛选 -->
    <attrFilter ref="attrFilterRef" v-model:isOpen="isOpen" :filterData="filterData" @changeAttr="changeAttr" />

    <!-- 商品详情-选具体的sku -->
    <prodDetail :optionInfo="optionInfoDetail" @close="close" />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed, inject } from "vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
const route = useRoute();
import { Search } from "@element-plus/icons-vue";
import prodDetail from "./prodDetail.vue";
import attrFilter from "./attrFilter.vue";
import {
  categoryList,
  getPage,
  getSpListNewpage,
  getProductDetail,
  getTempProductList,
  queryStastsList,
  queryCache
} from "@/apis/quote-price/following";
const currTempObj = ref(inject("currTemp")); //祖级传递过来的当前模板obj

const attrFilterRef = ref();
const sorts = ref([
  {
    sortType: 1, //1-销量 2-价格 3-新品
    sortTypeValue: 1 //0-升序 1-降序
  },
  {
    sortType: 2, //1-销量 2-价格 3-新品
    sortTypeValue: 1 //0-升序 1-降序
  },
  {
    sortType: 3, //1-销量 2-价格 3-新品
    sortTypeValue: 1 //0-升序 1-降序
  }
]);
const currentSort = ref({
  sortType: 0, //0-默认排序 1-销量 2-价格 3-新品
  sortTypeValue: 1 //0-升序 1-降序
});
const minPrice = ref(null);
const maxPrice = ref(null);
const searchkey2 = ref("");

const visible = ref(false);
const treeData = ref([]);
const list = ref([]);
const optionInfoDetail = ref({
  isShow: false,
  detail: {}
});
const isOpen = ref(false); //是否打开更多筛选抽屉
const filterData = ref([]);
const pagination = ref({
  page: 1,
  size: 50,
  total: 0
});

const emit = defineEmits(["update:isOpen", "close", "changeCate"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isMounted: false, //是否需要执行onMounted
        isShow: false,
        activeName: null, //1-条件内 2-条件外
        productType: -1 //1-主材 2-辅材
      };
    }
  }
});
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

//查询分类tree
const categoryListFun = async () => {
  await categoryList({}).then(res => {
    if (res.code === 200) {
      treeData.value = res.data;
    }
  });
};

watch(
  () => props.optionInfo,
  val => {
    // console.log("是否需要执行onMounted", props.optionInfo);
    if (val.isMounted) {
      categoryListFun();
    }
  },
  { deep: true, immediate: true }
);

onMounted(async () => {
  // categoryListFun();
});

//属性筛选id改变时的回调
const _filterVal = ref([]);
const _filterVal3 = ref([]);
const _brandIds = ref([]);
const changeAttr = ({ filterVal, filterVal3, brandIds }) => {
  console.log("子组件返回的数据===", filterVal, filterVal3, brandIds);
  _filterVal.value = filterVal;
  _filterVal3.value = filterVal3;
  _brandIds.value = brandIds;

  const attrIds2 = _filterVal.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = _filterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && _filterVal3.value.push(ids2);
  }
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getList(); //属性筛选接口请求
};

//筛选属性-列表查询
const queryStastsListFun = () => {
  queryStastsList({
    categoryId: currCate.value.categoryId,
    productType: props.optionInfo.productType === 1 ? null : props.optionInfo.productType === 2 ? 2 : 0 //  2-查询辅材  null-查询主材 0-查询全部
  }).then(res => {
    if (res.code === 200) {
      filterData.value = res.data;
    }
  });
};
/**
 *
 * @param isClearSelected  是否需要清空选中的sku
 */
const reset = (isClearSelected = true) => {
  currentSort.value = {
    sortType: 0, //0-默认排序 1-销量 2-价格 3-新品
    sortTypeValue: 1 //0-升序 1-降序
  };
  minPrice.value = null;
  maxPrice.value = null;
  searchkey2.value = "";
  if (isClearSelected) selected.value = [];

  _filterVal.value = [];
  _filterVal3.value = [];
  _brandIds.value = [];

  //清空组件筛选
  attrFilterRef.value.reset();
};

const openSku = item => {
  getProductDetail({ productId: item.productId }).then(res => {
    if (res.code === 200) {
      optionInfoDetail.value.isShow = true;
      optionInfoDetail.value.detail = res.data;
      optionInfoDetail.value.activeName = props.optionInfo.activeName;
    }
  });
};
const selected = ref([]); //选中的sku

const close = () => {
  optionInfoDetail.value.isShow = false;
  console.log("查询暂存的商品sku", JSON.parse(localStorage.getItem("followingObj"))._time);
  getTempProductListFun();
};
//查询暂存的商品sku
const getTempProductListFun = () => {
  if (props.optionInfo.activeName) {
    queryCache({ code: JSON.parse(localStorage.getItem("followingObj"))._time }).then(res => {
      if (res.code === 200) {
        selected.value = res.data || [];
        emit("changeCate", { total: pagination.value.total, selected: selected.value });
      }
    });
  } else {
    getTempProductList({ code: JSON.parse(localStorage.getItem("followingObj"))._time }).then(res => {
      if (res.code === 200) {
        selected.value = res.data || [];
        emit("changeCate", { total: pagination.value.total, selected: selected.value });
      }
    });
  }
};

// 更改排序项 销量、价格、新品
const changeSort = sortType => {
  if (currentSort.value.sortType === sortType) {
    // 点击的是同一个排序项，需要更改升序、降序
    currentSort.value.sortTypeValue = currentSort.value.sortTypeValue === 0 ? 1 : 0;
  } else {
    // 点击的是另一个排序项，直接更改当前排序对象，降序
    const obj = sorts.value.filter(item => item.sortType === sortType)[0];
    currentSort.value = obj;
  }
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getList();
};

const changeMinPrice = val => {
  if (Number(val) > Number(maxPrice.value) && maxPrice.value) {
    ElMessage({
      message: "最小值必须<最大值",
      type: "error",
      offset: 60
    });
    if (maxPrice.value && minPrice.value) minPrice.value = null;
  } else {
    if ((maxPrice.value && minPrice.value) || (!maxPrice.value && !minPrice.value)) {
      resetPagination(); //清空页面上的list数据，重置page=1 size=50
      getList(); //进行属性值筛选，并重置页码
    }
  }
};
const changeMaxPrice = val => {
  if (Number(val) < Number(minPrice.value) && minPrice.value) {
    ElMessage({
      message: "最大值必须>最小值",
      type: "error",
      offset: 60
    });
    if (maxPrice.value && minPrice.value) maxPrice.value = null;
  } else {
    if ((maxPrice.value && minPrice.value) || (!maxPrice.value && !minPrice.value)) {
      resetPagination(); //清空页面上的list数据，重置page=1 size=50
      getList(); //进行属性值筛选，并重置页码
    }
  }
};

//分类更改
const currCate = ref({}); //当前选中的分类
const oldNode = ref({ categoryId: null });
const handleNodeClick = async val => {
  // console.log("当前分类===", val);
  if (val.children.length > 0) return;
  currCate.value = val;
  if (oldNode.value.categoryId !== val.categoryId) {
    reset(false);
    resetPagination(); //清空页面上的list数据，重置page=1 size=50
    getList();
  }

  oldNode.value = val;
};

//清空商品列表，并且清空选中的tree节点
const resetPageList = () => {
  currCate.value = {};
  list.value = [];
};

const load = () => {
  console.log("触底了，要请求分页查询接口 getList();");
  if (list.value.length < pagination.value.total) {
    pagination.value.page++;
    getList();
  }
};

const resetPagination = () => {
  list.value = [];
  pagination.value.page = 1;
  pagination.value.size = 50;
};

const refresh = () => {
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getList();
};

//分类查询商品列表  isClear-在查询之前，是否清空list数据
const getList = async (isClear = false) => {
  if (currCate.value.categoryId) {
    if (isClear) list.value = [];
    await getSpListNewpage({
      categoryId: currCate.value.categoryId,
      sortType: currentSort.value.sortType,
      sortTypeValue: currentSort.value.sortTypeValue,
      minPrice: minPrice.value,
      maxPrice: maxPrice.value,
      searchKey: searchkey2.value,
      stastsIdsStr: _filterVal3.value, //属性筛选ids
      brandIds: _brandIds.value, //品牌id
      page: pagination.value.page,
      size: pagination.value.size,
      productType:
        currTempObj.value?.softDecorationStatus === 1 || route.query?.softDecorationStatus === "1"
          ? 1
          : props.optionInfo.productType === 1
            ? null
            : props.optionInfo.productType === 2
              ? 2
              : 0 //  2-查询辅材  null-查询主材 0-查询全部
    }).then(res => {
      if (res.code === 200) {
        list.value = [...list.value, ...res.data.list];
        pagination.value.total = res.data.total;

        queryStastsListFun(); //查询属性筛选数据
        emit("changeCate", { total: res.data.total, selected: selected.value });
      }
    });
  }
};

const clickClose = () => {
  _isOpen.value = false;
  // emit("close");
};

defineExpose({ reset, getList, refresh, getTempProductListFun, resetPageList, categoryListFun });
</script>

<style lang="scss"></style>
<style lang="scss" scoped>
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }

  .el-tree-node__content {
    line-height: 32px;
    height: 32px;
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #eef1f4 !important;
    color: #1a1a1a;

    .custom-tree-node i {
      color: #1a1a1a !important;
    }
  }
}

.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}
.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;
  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
.products-list-wrap {
  height: 600px;
  overflow: auto;
  :deep(.el-container) {
    height: 100%;
  }
  :deep(.el-aside) {
    padding-top: 10px;
  }
  :deep(.el-main) {
    border-left: 1px solid #e2e8f0;
    padding: 0 20px;
    & > .left {
      .action-wrap {
        position: sticky;
        top: 0;
        z-index: 2;
        background-color: white;
        height: 72px;
        display: flex;
        align-items: center;
        .sort-wrap {
          display: flex;
          align-items: center;
          .active {
            background-color: #424e66;
            color: white;
          }
          i {
            font-style: normal;
            display: inline-block;
            margin: 0 4px;
          }
          & > div {
            display: flex;
            align-items: center;
          }
          .right {
            & > div {
              display: flex;
              align-items: center;
            }
          }
        }
      }
      .list-wrap {
        display: flex;
        flex-wrap: wrap;
      }
    }
  }
}
</style>
